﻿using System;
using System.Web.Mvc;
using NHibernate;
using Web.Extensions;
using Web.Model;
using Web.Security;
using Web.ViewModels;
using Web.HelperClasses;

namespace Web.Controllers
{

    public class IdeaController : Controller
    {
    	public IdeaController(IAuthorizationService authz, ISession session, IUserSession userSession)
    	{
    		this.authz = authz;
    		this.session = session;
    		this.userSession = userSession;
    	}

		[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Head)]
        public ActionResult Index()
        {
			if (!authz.Authorize(Operation.ApproveProject)) throw new UnauthorizedAccessException();
			var ideas = session.CreateCriteria<Idea>().List<Idea>();
            return View(ideas);
        }

		[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Head)]
		public ActionResult View(int Id)
		{
			if (!authz.Authorize(Operation.ApproveProject)) throw new UnauthorizedAccessException();

			var idea = session.Get<Idea>(Id);
			var users = session.CreateCriteria<User>().List<User>();
			ViewBag.Users = users;
			ViewBag.SelectedUserId = idea.Author == null ? userSession.CurrentUser.Id : idea.Author.Id;

			return View(idea);
		}

		[HttpPost]
		public ActionResult Create(CreateIdeaForm form, string returnUrl)
		{
            if (!ModelState.IsValid) throw new ArgumentException("Неверный формат данных");
			if (form.BeginningDate < DateTime.Today.AddDays(1))
                throw new ArgumentException(String.Format("Новый проект может начинаться не раньше чем {0}", DateTime.Now.AddDays(1).ToShortDateString()));
            if (form.BeginningDate > DateTime.Today.AddMonths(1))
                throw new ArgumentException(String.Format("Новый проект может начинаться не позже чем {0}", DateTime.Now.AddMonths(1).ToShortDateString()));
			var idea = new Idea()
				{
					Name = form.Name,
                    Description = form.Description,
					Author = userSession.CurrentUser,
                    BeginningDate = form.BeginningDateTime
				};
			session.Save(idea);
            AdminNotifier notifier = new AdminNotifier(session);
            notifier.NotifyIdeaCreated(idea);
			return Json(new { RedirectUrl = returnUrl ?? Url.Action("Index", "Home") });
		}

		[HttpPost]
		public ActionResult Approve(int id, int organizerId)
		{
			if (!authz.Authorize(Operation.ApproveProject)) throw new UnauthorizedAccessException();
			var idea = session.Get<Idea>(id);
			var project = new Project()
				{
					Name = idea.Name,
					Description = idea.Description,
                    Beginning = idea.BeginningDate,
                    Ending = idea.BeginningDate,
					Organizer = session.Load<User>(organizerId)
				};
			session.Delete(idea);
			session.Save(project);
            ProjectNotifier notifier = new ProjectNotifier(project, session);
            notifier.NotifyProjectApproved();
			return RedirectToAction("Index");
		}

		[HttpPost]
		public ActionResult Decline(int Id)
		{
			if (!authz.Authorize(Operation.ApproveProject)) throw new UnauthorizedAccessException();
			var idea = session.Get<Idea>(Id);
			session.Delete(idea);
			return RedirectToAction("Index");
		}


		readonly IAuthorizationService authz;
    	readonly ISession session;
    	readonly IUserSession userSession;
    }
}
